package main

import (
	"errors"
	"fmt"
	"net/http"
	"strconv"
	"strings"

	// "github.com/GoAdminGroup/go-admin/modules/db"
	"github.com/gin-gonic/gin"
)

func init() {
	R.SetFuncMap(funcMap)
	R.GET("/", webIndex)
	R.GET("/content/:id", funcOneContent)
	R.GET("/page/:pageNo", webIndex)
	R.GET("/page/:pageNo/", webIndex)

	// 查看标签
	R.GET("/tag/:urlPathParam", funcListTags)
	R.GET("/tag/:urlPathParam/", funcListTags)
	R.GET("/tag/:urlPathParam/page/:pageNo", funcListTags)
	R.GET("/tag/:urlPathParam/page/:pageNo/", funcListTags)
	// 异常页面
	R.GET("/error", fnError)

	//初始化导航菜单路由
	// 在main.go中等数据库初始化完毕后调用
	// initCategoryRoute()
}

func webIndex(c *gin.Context) {
	// conn := Eng.SqliteConnection()
	// data, _ := db.WithDriverAndConnection("pbootcms", conn).
	// 	Table(tableCategoryName).Select("name").All()
	data := warpRequestMap(c)
	cHtml(c, http.StatusOK, "index.html", gin.H{
		// "data":  data,
		"data": data,
		"q": data["q"].(string),
		"pageNo": data["pageNo"].(int),
	})
}

func fnError(c *gin.Context) {
	cHtml(c, http.StatusOK, "error.html", nil)
}

// funcListCategory 导航菜单数据列表
func funcListCategory(c *gin.Context) {
	data := warpRequestMap(c)
	urlPathParam := c.Param("urlPathParam")
	if urlPathParam == "" { //导航菜单路径访问,例如:/web
		urlPathParam = c.GetString("urlPathParam")
	}
	data["UrlPathParam"] = urlPathParam
	templateFile, err := findThemeTemplate(tableCategoryName, urlPathParam)
	if err != nil || templateFile == "" {
		templateFile = "category.html"
	}
	cHtml(c, http.StatusOK, templateFile, data)
}

// funcListTags 标签列表
func funcListTags(c *gin.Context) {
	data := warpRequestMap(c)
	urlPathParam := c.Param("urlPathParam")

	data["UrlPathParam"] = urlPathParam
	cHtml(c,http.StatusOK, "tag.html", data)
}

// funcOneContent 查询一篇文章
func funcOneContent(c *gin.Context) {
	data := warpRequestMap(c)
	urlPathParam := c.Param("urlPathParam")
	id:=c.Param("id")
	if urlPathParam == "" { //导航菜单路径访问,例如:/web/nginx-use-hsts
		urlPathParam = c.GetString("urlPathParam")
	}
	data["UrlPathParam"] = urlPathParam
	data["id"] = id

	templateFile, err := findThemeTemplate(tableContentName, urlPathParam)
	if err != nil || templateFile == "" {
		templateFile = "content.html"
	}
	cHtml(c,http.StatusOK, templateFile, data)
}

// initCategoryRoute 初始化导航菜单的映射路径
func initCategoryRoute() {
	categories, _ := findAllCategory()
	for i := range categories {
		category := categories[i]
		categoryID := fmt.Sprint(category["id"])
		addCategoryRoute(categoryID)
	}
}

// addCategoryRoute 增加导航菜单的路由
func addCategoryRoute(categoryID string) {

	// 处理重复注册路由的panic,不对外抛出
	defer func() {
		if r := recover(); r != nil {
			panicMessage := fmt.Sprintf("%s", r)
			FuncLogPanic(nil, errors.New(panicMessage))
		}
	}()

	//导航菜单的访问映射
	R.GET(funcTrimSuffixSlash(categoryID), addListCategoryRoute(categoryID))
	R.GET(categoryID, addListCategoryRoute(categoryID))
	//导航菜单分页数据的访问映射
	R.GET(categoryID+"page/:pageNo", addListCategoryRoute(categoryID))
	R.GET(categoryID+"page/:pageNo/", addListCategoryRoute(categoryID))
	//导航菜单下文章的访问映射
	R.GET(categoryID+":contentURI", addOneContentRoute(categoryID))
	R.GET(categoryID+":contentURI/", addOneContentRoute(categoryID))
}

// addListCategoryRoute 增加导航菜单的GET请求路由,用于自定义设置导航的路由
func addListCategoryRoute(categoryID string) gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Set("urlPathParam", categoryID)
		funcListCategory(c)
	}
}

// addOneContentRoute 增加内容的GET请求路由
func addOneContentRoute(categoryID string) gin.HandlerFunc {
	return func(c *gin.Context) {
		contentURI := c.Param("contentURI")
		key := categoryID + contentURI
		c.Set("urlPathParam", key)
		funcOneContent(c)
	}
}

// warpRequestMap 包装请求参数为map
func warpRequestMap(c *gin.Context) map[string]interface{} {
	pageNoStr := c.Param("pageNo")
	if pageNoStr == "" {
		pageNoStr = c.GetString("pageNo")
	}
	if pageNoStr == "" {
		//pageNoStr = c.DefaultQuery("pageNo", "1")
		pageNoStr = "1"
	}

	pageNo, _ := strconv.Atoi(pageNoStr)
	q := strings.TrimSpace(c.Query("q"))

	idstr := c.Param("id")
	id, _ := strconv.Atoi(idstr)

	data := make(map[string]any, 0)
	data["pageNo"] = pageNo
	data["q"] = q
	data["id"] = id
	//设置用户角色,0是访客,1是管理员
	userType, ok := c.Get(userTypeKey)
	if ok {
		data[userTypeKey] = userType
	} else {
		data[userTypeKey] = 0
	}
	return data
}
